package org.mokusakura.web.filter;

import org.mokusakura.constant.SessionAttributeKeyConstant;
import org.mokusakura.domain.User;
import org.mokusakura.service.HistoryService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;

@WebFilter(filterName = "HistoryFilter", urlPatterns = {"/Category", "/Item", "/Product"})
public class HistoryFilter implements Filter {
    private HistoryService historyService;

    @Override
    public void init(FilterConfig config) {
        WebApplicationContext requiredWebApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(
                config.getServletContext());
        historyService = requiredWebApplicationContext.getBean(HistoryService.class);
    }


    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException,
            IOException {
        if (historyService != null && req instanceof HttpServletRequest && resp instanceof HttpServletResponse) {

            HttpServletRequest request = (HttpServletRequest) req;
            User loginUser = (User) request.getSession().getAttribute(SessionAttributeKeyConstant.LOGIN_USER);
            if (loginUser != null) {
                String categoryID = req.getParameter("categoryID");
                String productID = req.getParameter("productID");
                String itemID = req.getParameter("itemID");
                if (categoryID != null) {
                    historyService.addHistory(loginUser, categoryID, new Timestamp(System.currentTimeMillis()));
                } else if (productID != null) {
                    historyService.addProductHistory(loginUser, productID, new Timestamp(System.currentTimeMillis()));
                } else {
                    historyService.addItemHistory(loginUser, itemID, new Timestamp(System.currentTimeMillis()));
                }
            }
        }
        chain.doFilter(req, resp);
    }


}
